﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class ForumTopicList : BaseUserControl
    {
        public ForumSearchCriteria SearchCriteria { get; set; }

        private static string FirstPositionLocalized = "FirstPosition".ToLocalizedString();
        private static string TopicIsNotStickyLocalized = "TopicIsNotSticky".ToLocalizedString();

        private static string forumsearchLocalized = "forumsearch".ToLocalizedString();
        private static string searchLocalized = "searchResult".ToLocalizedString();
        private static string lastpostLocalized = "lastpost".ToLocalizedString();
        private static string orphanLocalized = "orphan".ToLocalizedString();
        private static string lasttopicLocalized = "lasttopic".ToLocalizedString();
        private static string unreadLocalized = "unread".ToLocalizedString();

        private Int32 UserRightLevel { get; set; }
        private Int32 ForumCategoryId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            HyperLink1.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/forum";
            HyperLink2.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/forum";

            HyperLink3.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/forumsearch";
            HyperLink4.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/lastpost";
            HyperLink5.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/orphan";
            HyperLink6.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/lasttopic";
            HyperLink7.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/lastpost";
            HyperLink8.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/forumsearch";
            HyperLink9.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/lasttopic";
            HyperLink10.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/orphan";

            UnreadHyperLink.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/unread";
            UnreadHyperLink2.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/topic/unread";
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            // Affichage d'une liste de sujets de discussion.
            DataSet ds = new DataSet();
            System.IO.StringReader xmlSR = null;
            String viewType = String.Empty;

            if (Page.RouteData.Values["viewType"] != null)
                viewType = Page.RouteData.Values["viewType"].ToString();
            else
            {
                viewType = "bycategory";
            }

            if (viewType != null && viewType != String.Empty)
                switch (viewType)
                {
                    case "forumsearch":
                        TopicListUpdatePanel.Visible = false;
                        ucForumSearch1.Visible = true;
                        this.Page.Title = prefixTitle + forumsearchLocalized;
                        return;
                    case "bycategory":
                        //Todo : Intercepter avec un TryParse l'erreur : Value was either too large or too small for an Int32.  
                        this.ForumCategoryId = Int32.Parse(Page.RouteData.Values["categoryId"].ToString());

                        var ThisCategory = ForumCategoryDal.GetEntity(ForumCategoryId);

                        if (ThisCategory == null)
                            throw new HttpException(404, "This category don't exists.");

                        ForumTopicSetEntityDataSource1.WhereParameters["ForumCategoryIdParam"].DefaultValue = ForumCategoryId.ToString();
                        XmlForumTopic.GroupingText = XmlForumTopic.GroupingText + " " + ForumCategoryDal.GetEntity(ForumCategoryId).LabelForumCategory;
                        // Topic d'une catégorie
                        xmlSR = new System.IO.StringReader(ForumTopicView.GetXmlEntities(ForumCategoryId, (Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));

                        this.UserRightLevel = UserAccessDal.UserRightLevel(ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
                        if (this.UserRightLevel == 0)
                            Response.Redirect("~/" + ThisMaster.RequesterCulture + "/connexion/?returnurl=~" + Request.RawUrl);

                        TopicCreatePanel1.Visible = UserRightLevel > RightLevel.Reader;

                        this.Page.Title = prefixTitle + ThisCategory.LabelForumCategory;
                        break;
                    case "unread":
                        //Topic non lu par currentuser
                        xmlSR = new System.IO.StringReader(ForumTopicView.GetUnreadXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));
                        this.Page.Title = prefixTitle + unreadLocalized;
                        break;
                    case "lasttopic":
                        //Topic les plus recents
                        xmlSR = new System.IO.StringReader(ForumTopicView.GetLastTopicCreateXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));
                        this.Page.Title = prefixTitle + lasttopicLocalized;
                        break;
                    case "lastpost":
                        //Topic les plus recents
                        xmlSR = new System.IO.StringReader(ForumTopicView.GetLastPostCreateXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));
                        this.Page.Title = prefixTitle + lastpostLocalized;
                        break;
                    case "orphan":
                        //Topic sans réponse : 1 message et sujet non-vérouillé
                        xmlSR = new System.IO.StringReader(ForumTopicView.GetOrphanXmlEntities((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));
                        this.Page.Title = prefixTitle + orphanLocalized;
                        break;
                    case "search":
                        //Recherche sur mot-clefs et liste d'auteurs
                        var criteria = Session["criteria"] as ForumSearchCriteria;
                        xmlSR = new System.IO.StringReader(ForumTopicView.SearchByKeywordsAndAuthors(criteria.Keywords, criteria.Authors, (Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString(), ThisMaster.RequesterTimeZone));
                        Session["criteria"] = null;
                        this.Page.Title = prefixTitle + searchLocalized;
                        break;
                    default:
                        break;
                }

            ChangeCategoryDropDownList1.DataSource = UserAccessDal.GetForumCategoryAllowedLookup((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString());
            ChangeCategoryDropDownList1.DataBind();
            ChangeCategoryDropDownList2.DataSource = UserAccessDal.GetForumCategoryAllowedLookup((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString());
            ChangeCategoryDropDownList2.DataBind();

            if (this.ForumCategoryId > 0)
            {
                ChangeCategoryDropDownList1.SelectedValue = this.ForumCategoryId.ToString();
                ChangeCategoryDropDownList2.SelectedValue = this.ForumCategoryId.ToString();
            }

            ds.ReadXml(xmlSR);
            TopicListView.DataSource = ds.Tables["Topic"];
            TopicListView.DataBind();

            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu
            if (Session["AnonymousID"] == null)
            {
                UnreadHyperLink.Visible = true;
                UnreadHyperLink2.Visible = true;
            }
            else
            {
                UnreadHyperLink.Visible = false;
                UnreadHyperLink2.Visible = false;
            }
        }

        protected void TopicListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            HyperLink forumPostHyperLink;
            ListView LastPostListView;
            DataRowView drv;
            ListViewItem item = e.Item;
            DataView view = null;
            Button btn, btn2;

            if (item.ItemType == ListViewItemType.DataItem)
            {
                btn = e.Item.FindControl("EditForumTopicButton") as Button;
                btn2 = e.Item.FindControl("DeleteForumTopicButton") as Button;

                // ForumPostHyperLink.NavigateUrl contient ForumTopicId
                forumPostHyperLink = (HyperLink)item.FindControl("ForumPostHyperLink");

                if (ThisMaster.RequesterProfile != null && ThisMaster.RequesterProfile.UserName.ToLower() == ForumTopicDal.GetEntity(Int32.Parse(forumPostHyperLink.NavigateUrl)).AuthorForumTopic.ToLower()
                    && btn != null && btn.CommandName == String.Empty)
                {
                    btn.Visible = true;
                    btn.CommandName = "EditCommand";
                    if (forumPostHyperLink.NavigateUrl != null && forumPostHyperLink.NavigateUrl != String.Empty)
                        btn.CommandArgument = forumPostHyperLink.NavigateUrl;
                }

                if (ThisMaster.RequesterProfile != null && (ThisMaster.RequesterRoles.Contains("RoleAdminForum") || ThisMaster.RequesterProfile.UserName.ToLower() == ForumTopicDal.GetEntity(Int32.Parse(forumPostHyperLink.NavigateUrl)).AuthorForumTopic.ToLower())
                    && btn2 != null && btn2.CommandName == String.Empty)
                {
                    btn2.Visible = true;
                    btn2.CommandName = "Delete";
                    if (forumPostHyperLink.NavigateUrl != null && forumPostHyperLink.NavigateUrl != String.Empty)
                        btn2.CommandArgument = forumPostHyperLink.NavigateUrl;
                }

                if (forumPostHyperLink != null)
                {
                    forumPostHyperLink.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/forumpost/" + forumPostHyperLink.NavigateUrl +
                        "/?topicpagenumber=" + ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty);
                }
                LastPostListView = (ListView)item.FindControl("LastPostListView");
                drv = (DataRowView)item.DataItem;

                if (drv != null && drv.DataView.Table.ChildRelations.Count > 0)
                    view = drv.CreateChildView("Topic_LastPost");

                if (view != null)
                {
                    LastPostListView.DataSource = view;
                    LastPostListView.DataBind();
                }
            }
        }

        protected void TopicListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                var ForumTopicId = Int32.Parse(e.CommandArgument.ToString());
                var ForumTopicEditing = ForumTopicDal.GetEntity(ForumTopicId);

                ForumTopicIdLabel.Text = ForumTopicId.ToString();
                LabelTopicTextBox.Text = ForumTopicEditing.LabelForumTopic;
                IsStickyForumTopicCheckBox.Checked = ForumTopicEditing.OrderForumTopic > 0;
                InsertBeforeStickyTopicDropDownList.SelectedValue = (ForumTopicEditing.OrderForumTopic == 0) ?
                    "0" :
                    (ForumTopicEditing.OrderForumTopic + 10).ToString();

                this.UserRightLevel = UserAccessDal.UserRightLevel(ForumCategoryDal.GetCategoryIdByTopicId(ForumTopicId), "");
                if (this.UserRightLevel == RightLevel.Moderator || ThisMaster.RequesterProfile.UserName.ToLower() == ForumTopicEditing.AuthorForumTopic.ToLower())
                {
                    CategoryDropDownListLabel.Visible = true;
                    CategoryDropDownList.Visible = true;
                }
                CategoryDropDownList.SelectedValue = ForumCategoryDal.GetCategoryIdByTopicId(ForumTopicId).ToString();
                this.Page.SetFocus(AddTopicPopupButton.ClientID);
            }

            if (e.CommandName == "Delete")
            {
                ForumTopicDal.DeleteEntity(Int32.Parse(e.CommandArgument.ToString()));
            }
        }

        protected void TopicListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {

        }

        protected void TopicListView_ItemDeleted(object sender, ListViewDeletedEventArgs e)
        {
            InsertBeforeStickyTopicDropDownList.DataBind();
        }

        protected void LastPostListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            TextBox forumCategoryIdLabel;
            HyperLink lastPostHyperLink;

            forumCategoryIdLabel = (TextBox)((ListViewItem)e.Item).FindControl("ForumCategoryIdLabel");
            lastPostHyperLink = (HyperLink)((ListViewItem)e.Item).FindControl("LastPostHyperLink");

            if (lastPostHyperLink != null && forumCategoryIdLabel != null)
                lastPostHyperLink.NavigateUrl = "~/" + ThisMaster.RequesterCulture + "/forumpost/showpost/" + ((DataRowView)e.Item.DataItem).Row.ItemArray[3].ToString() +
                    "/?topicpagenumber=" + ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty);
        }

        protected void AddTopicPopupButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid) return;

            Int32 id = Int32.Parse(ForumTopicIdLabel.Text);

            ForumTopic forumTopicToUpdate = new ForumTopic()
            {
                Id = id,
                LabelForumTopic = LabelTopicTextBox.Text,
                AuthorForumTopic = ThisMaster.RequesterProfile.UserName,
                NumberHasBeenSeenForumTopic = 0,
            };

            if (LabelTopicTextBox.Text != string.Empty)
            {
                if (id == 0)
                {
                    forumTopicToUpdate.OrderForumTopic = (IsStickyForumTopicCheckBox.Checked) ?
                   (Int32.Parse((InsertBeforeStickyTopicDropDownList.SelectedValue == String.Empty) ? "10" : InsertBeforeStickyTopicDropDownList.SelectedValue)) : 0;
                    forumTopicToUpdate.ForumCategory = ForumCategoryDal.GetEntity(Int32.Parse(Page.RouteData.Values["categoryId"].ToString()));
                    id = ForumTopicDal.CreateEntity(forumTopicToUpdate);
                    Response.Redirect("~/" + ThisMaster.RequesterCulture + "/forumpost/" + id);
                }
                else
                {
                    forumTopicToUpdate.OrderForumTopic = (IsStickyForumTopicCheckBox.Checked) ?
                   (Int32.Parse((InsertBeforeStickyTopicDropDownList.SelectedValue == String.Empty) ? "10" : InsertBeforeStickyTopicDropDownList.SelectedValue) - 10) : 0;
                    forumTopicToUpdate.ForumCategory = new ForumCategory() { Id = Int32.Parse(CategoryDropDownList.SelectedValue) };
                    ForumTopicDal.UpdateEntity(forumTopicToUpdate);
                    Response.Redirect("~/" + ThisMaster.RequesterCulture + "/topic/bycategory/" + ForumCategoryDal.GetCategoryIdByTopicId(id));
                }

                ForumTopicIdLabel.Text = "0";
                LabelTopicTextBox.Text = String.Empty;
                IsStickyForumTopicCheckBox.Checked = false;
                InsertBeforeStickyTopicDropDownList.DataBind();
            }
        }

        protected void InsertBeforeStickyTopicDropDownList_OnDataBound(object sender, EventArgs e)
        {
            if (InsertBeforeStickyTopicDropDownList.Items.Count > 0)
                InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = (Int32.Parse(InsertBeforeStickyTopicDropDownList.Items[0].Value) + 10).ToString() });
            else
                InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = FirstPositionLocalized, Value = "10" });

            InsertBeforeStickyTopicDropDownList.Items.Insert(0, new ListItem() { Text = TopicIsNotStickyLocalized, Value = "0" });
        }

        protected void ChangeCategoryDropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/" + ThisMaster.RequesterCulture + "/topic/bycategory/" + ChangeCategoryDropDownList1.SelectedValue);
        }

        protected void ChangeCategoryDropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("~/" + ThisMaster.RequesterCulture + "/topic/bycategory/" + ChangeCategoryDropDownList2.SelectedValue);
        }
    }
}